package com.sxm.yiwei.tools;

import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.FileProvider;
import android.util.Log;

import com.sxm.yiwei.activitis.AppManager;
import com.sxm.yiwei.activitis.HotSendActivity;
import com.sxm.yiwei.activitis.OnceSendActivity;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.DateFormat;
import java.util.Calendar;
import java.util.Locale;

/**
 * 图片处理(压缩<100k)
 * Created by KuKa on 2017/7/29.
 */

public class CropPictures {

    /**
     *
     * 把图片保存到本地
     * @param bitmap
     *
     */

    private static final int REQUEST_EXTERNAL_STORAGE = 1;


    public static String saveBitmapFile(Bitmap bitmap,String name){
        String[] PERMISSIONS_STORAGE = {
                android.Manifest.permission.READ_EXTERNAL_STORAGE,
                android.Manifest.permission.WRITE_EXTERNAL_STORAGE
        };
        int permission = ActivityCompat.checkSelfPermission(AppManager.getAppManager().currentActivity(), android.Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (permission != PackageManager.PERMISSION_GRANTED) {
            // We don't have permission so prompt the user
            ActivityCompat.requestPermissions(
                    AppManager.getAppManager().currentActivity(),
                    PERMISSIONS_STORAGE,
                    REQUEST_EXTERNAL_STORAGE

            );
        }

        File rootPath = new File(Environment.getExternalStorageDirectory()+"/YiviPic");
        File temp;
        File tempFile;
        rootPath.mkdirs();
       /* if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            Uri uri11 = FileProvider.getUriForFile(AppManager.getAppManager().currentActivity(), AppManager.getAppManager().currentActivity().getApplicationContext().getPackageName() + ".provider", rootPath);
            tempFile = new File(String.valueOf(uri11));
            //  大于等于24即为7.0及以上执行内容
        } else {
            //  低于24即为7.0以下执行内容
            tempFile  = new File(rootPath,name);
        }*/
        tempFile  = new File(rootPath,name);
        String path = tempFile.getAbsolutePath();

        //创建一个输出流，将数据写入到创建的文件对象中。
        try {
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(tempFile));
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
            bos.flush();
            //关闭流对象
            bos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return path;
    }
}
